import Taro, {getCurrentInstance} from "@tarojs/taro";


export async function getWxCode() {
    const response = await Taro.login();
    if (response.errMsg === "login:ok") return response.code;
}

export async function getImageInfo(src) {
    return new Promise((resolve) => {
        Taro.getImageInfo({
            src, success: ({width, height, ...rest}) => resolve({width, height, ...rest}),
        });
    });
}

export async function openLocation(lat, lng, name, address) {
    Taro.openLocation({
        latitude: Number(lat),
        longitude: Number(lng),
        name,
        address
    });
}

export function getLocation() {
    return new Promise((resolve) => {
        Taro.getLocation({
            type: "gcj02", success: (res) => resolve(res), fail: () => resolve(),
        });
    });
}

export function getFuzzyLocation() {
    return new Promise((resolve) => {
        Taro.getFuzzyLocation({
            type: "gcj02", success: (res) => resolve(res), fail: () => resolve(),
        });
    });
}


export function getStorageSync(key) {
    return Taro.getStorageSync(key);
}

export function successToast(title) {
    Taro.showToast({title});
}

export function failToast(title) {
    Taro.showToast({
        icon: "none", image: "/_framework/asserts/fail.png", title,
    });

}

export function infoToast(title) {
    Taro.showToast({icon: "none", title});
}

export function showLoading() {
    Taro.showLoading({title: "加载中"});
}

export function titleLoading(title) {
    Taro.showLoading({title});
}

export function hideLoading() {
    Taro.hideLoading();
}

export async function navigateTo(project, url, params = "") {
    await Taro.navigateTo({url: path(project, url) + (params && "?") + params});
}


export async function navigateBack(delta = 1) {
    await Taro.navigateBack({delta});
}

export async function redirectTo(project, url, params = "") {
    await Taro.redirectTo({url: path(project, url) + (params && "?") + params});
}

export async function reLaunch(project, url) {
    await Taro.reLaunch({url: path(project, url)});
}

function path(project, url) {
    return `/${project}/pages/${url}/index`;
}

export function barTitle(title) {
    Taro.setNavigationBarTitle({title});
}

export function message(tmplId) {
    return new Promise((resolve) => {
        Taro.requestSubscribeMessage({
            tmplIds: [tmplId], success: (res) => resolve(res),
        });
    });
}

export function getParams() {
    return getCurrentInstance().router.params;
}





